package com.jxpanda.spring.module.auth.core.user;


import com.jxpanda.infrastructure.core.tollkit.StringKit;
import lombok.Getter;

import java.util.Objects;

@Getter
public class WechatOAuth2User extends AbstractOAuth2User {

    public static final String OPEN_ID_KEY = "openid";
    public static final String UNION_ID_KEY = "unionid";

    private final String openId;

    private final String unionId;

    public WechatOAuth2User(String openId, String unionId, String userIdAttributeName) {
        super(userIdAttributeName);

        this.openId = Objects.requireNonNullElse(openId, "");
        this.attributes.put(OPEN_ID_KEY, openId);

        this.unionId = Objects.requireNonNullElse(unionId, "");
        this.attributes.put(UNION_ID_KEY, unionId);
    }


    @Override
    public String getName() {
        return getAttributes()
                .get(this.getUserIdAttributeName())
                .toString();
    }

    @Override
    public String getUserIdAttributeName() {
        // 如果通过配置文件配置了，这个值就不会为null，因此这里只是一个容灾，如果外部没有配置，自动做一次判断
        if (userIdAttributeName == null) {
            // 如果没有设置获取用户名的字段，则使用unionid优先策略，否则使用对应的字段
            boolean hasUnionId = StringKit.isNotBlank(this.unionId);
            if (hasUnionId) {
                this.userIdAttributeName = UNION_ID_KEY;
            } else {
                this.userIdAttributeName = OPEN_ID_KEY;
            }
            this.attributes.put(AbstractOAuth2User.USER_ID_ATTRIBUTE_NAME, this.userIdAttributeName);
        }
        return userIdAttributeName;
    }
}
